var xmlDom = null;
var xmlDoc = null;
$(document).ready(function(){
	initFlowControl();
});

function initFlowControl()
{
	try
	{
		showLoading();
		var tableName = $('#tableName');
		var docId = $('#docId');
		var nodeId = $('#nodeId');
		var version = $('#version');
		var creatorId = $('#creatorId');
		var currentUserId = $('#currentUserId');
		var saveObjBtn = $('#saveObjBtn');
		var submitObjBtn = $('#submitObjBtn');
		var showFlowBtn = $('#showFlowBtn');
		var opinionTr = $('#opinionTr');
		var returnBackTr = $('#returnBackTr');
		var statusTr = $('#statusTr');
		var submitTr = $('#submitTr');
		var historyTr = $('#historyTr');
		ajaxAction('inner/flow/queryTableFlowRefById.action', 'post', 'frm', true, function(json){
			var obj = eval('(' + json + ')');
			var workFlow = obj.workFlow;
			if(workFlow != null)
			{
				//暂时
				//$('#testDiv').text(workFlow.contentStr);
				xmlDom = loadXmlFile(workFlow.contentStr);
				xmlDoc = xmlDom.documentElement;
				if(isNotNull(docId.val())) //修改
				{
					var currentNode = getOneElement('/flow/nodes/node[@id="' + nodeId.val() + '"]');
					if(currentNode != null)
					{
						var nodeAttr = currentNode.getAttribute('nodeAttr');
						$('#nodeAttr').val(nodeAttr);
						var permitReturn = currentNode.getAttribute('permitReturn');
						statusTr.css('display', 'block');
						historyTr.css('display', 'block');
						showFlowBtn.css('display', 'inline-block');
						initActors(nodeId.val()); //初始化参与者
						var actorsDiv = $('#actorsDiv');
						if('start' == nodeAttr)
						{
							var actors = currentNode.getAttribute('actors');
							if(currentUserId.val() == creatorId.val())
							{
								ajaxAction('inner/flow/startIsAuditor.action', 'post', {'auditorInfo':actors}, true, function(flag){
									if(flag)
									{
										saveObjBtn.css('display', 'inline-block');
									}
								});
								ajaxAction('inner/flow/taskIsAuditor.action', 'post', {'tableName':tableName.val(), 'docId':docId.val()}, true, function(flag){
									if(flag)
									{
										submitObjBtn.css('display', 'inline-block');
										if(isNotNull(actorsDiv.html()))
										{
											submitTr.css('display', 'block');
										}
									}
								});
							}
						}
						else if('task' == nodeAttr)
						{
							disabledAllComponent();
							var modifyCode = getChildNodeText(currentNode, 'modifyCode');
							eval(modifyCode);
							var data = {
									'tableName':tableName.val(),
									'docId':docId.val()
								};
							ajaxAction('inner/flow/taskIsAuditor.action', 'post', data, true, function(flag){
								if(flag)
								{
									submitObjBtn.css('display', 'inline-block');
									if(isNotNull(actorsDiv.html()))
									{
										submitTr.css('display', 'block');
									}
									opinionTr.css('display', 'block');
									if('true' == permitReturn)
									{
										returnBackTr.css('display', 'block');
									}
								}
							});
						}
						else if('end' == nodeAttr)
						{
							disabledAllComponent();
						}
					}
					else
					{
						alert('流程已更改，不存在该节点。');
					}
				}
				else //新增
				{
					var startNode = getOneElement('/flow/nodes/node[@nodeAttr="start"]');
					var actors = startNode.getAttribute('actors');
					ajaxAction('inner/flow/startIsAuditor.action', 'post', {'auditorInfo':actors}, true, function(flag){
						if(flag)
						{
							saveObjBtn.css('display', 'inline-block');
						}
					});
				}
			}
		});
	}
	catch (e) {
		alert(e);
	}
	finally
	{
		hideLoading();
	}
}

function getOneElement(xpath)
{
	return xmlDoc.selectSingleNode(xpath);
}

function getElements(xpath)
{
	return xmlDoc.selectNodes(xpath);
}

function checkOpinion()
{
	var opinion = $('#opinion');
	if(opinion.val().length > 150)
	{
		return false;
	}
	return true;
}

function submitObj()
{
	var flowBtn = $('.flowBtn');
	var returnBack = $('#returnBack');
	var actors = $('input:radio[name="auditorInfo"][checked]');
	if(!isNotNull(returnBack.val()) && actors.length == 0)
	{
		showMsg('请选择“提交至”或“退回至”。');
		return;
	}
	if(checkOpinion() == false)
	{
		showMsg('审批意见不能超过150字。');
		return;
	}
	if(saveObj(false))
	{
		flowBtn.attr('disabled', true);
		if(actors.length != 0)
		{
			var auditorInfoVal = actors.val();
			var toNodeId = auditorInfoVal.split('|')[2];
			var nodeId = $('#nodeId');
			var arrow = getOneElement('/flow/arrows/lineArrow[@from="' + nodeId.val() + '"][@to="' + toNodeId + '"]');
			var action = getChildNodeText(arrow, 'action');
			if(isNotNull(action))
			{
				eval(action);
			}
		}
		var url = 'inner/flow/submitDoc.action';
		ajaxAction(url, 'post', formName, true, function(result){
			var obj = eval(result);
			if(obj.result == 'failure')
			{
				showConfirm(obj.message, function(v){
					if(v == true)
					{
						window.location.reload();
					}
				});
			}
			else
			{
				if(submitCallback != undefined && submitCallback != null)
				{
					submitCallback();
				}
			}
		});
	}
}

function showFlow()
{
	var tableName = $('#tableName');
	var docId = $('#docId');
	var nodeId = $('#nodeId');
	var url = realPath + '/inner/flow/showFlow.action?tableName=' + tableName.val();
	url += '&docId=' + docId.val() + '&nodeId=' + nodeId.val();
	openWin(url, 1000, 700, 'yes', 'yes');
}

function initActors(currentNodeId)
{
	var tableName = $('#tableName');
	var docId = $('#docId');
	var actorsHtml = new Array();
	var groupDivTmp = '<div class="inlineBlock inline" style="float:left; margin:0px 5px 0px 0px;">';
	groupDivTmp += '<div class="inlineBlock inline" style="width:100%; font-weight:bold;">#NEXT_NODE#</div><br/>';
	groupDivTmp += '<div class="inlineBlock inline" style="width:100%; border:lightblue 1px solid;">#AUDITOR#</div></div>';
	ajaxAsync('inner/flow/queryTheSameAuditor.action', 'post', {'tableName':tableName.val(), 'docId':docId.val()}, true, function(result){
		var resultObj = evalObj(result);
		if('N' == resultObj.same) //如果不是同一节点
		{
			var auditor = resultObj.auditor;
			var next = resultObj.next;
			var nextName = resultObj.nextname;
			var namesReturn = '';
			ajaxAsync('inner/flow/queryActorName.action', 'post', {'actorStr':auditor}, true, function(nameStr){
				namesReturn = nameStr;
			});
			var value = auditor + '|' + next;
			var radio = createRadioAuditor(value, namesReturn);
			var groupDivAuditor = groupDivTmp.replace('#NEXT_NODE#', nextName);
			groupDivAuditor = groupDivAuditor.replace('#AUDITOR#', radio);
			actorsHtml.push(groupDivAuditor);
		}
		else if('Y' == resultObj.same)
		{
			var fromArrows = getElements('/flow/arrows/lineArrow[@from="' + currentNodeId + '"]');
			fromArrows = doArrowSort(fromArrows);
			var len = fromArrows.length;
			for(var i = 0; i < len; i++)
			{
				var arrowx = fromArrows[i];
				var toNodeId = arrowx.getAttribute('to');
				var condition = getChildNodeText(arrowx, 'condition');
				var conditionResult = eval(condition);
				if(conditionResult == false)
				{
					continue;
				}
				var toNode = getOneElement('/flow/nodes/node[@id="' + toNodeId + '"]');
				var actorsMode = toNode.getAttribute('actorsMode');
				var nodeAttr = toNode.getAttribute('nodeAttr');
				var nodeName = toNode.getAttribute('name');
				var actors = '';
				if('code' == actorsMode)
				{
					var auditorCode = getChildNodeText(toNode, 'auditorCode');
					actors = eval(auditorCode);
				}
				else if('select' == actorsMode)
				{
					actors = toNode.getAttribute('actors');
					var assignToUser = toNode.getAttribute('assignToUser');
					if('true' == assignToUser)
					{
						ajaxAsync('inner/flow/assignToUser.action', 'post', {'auditorInfo':actors}, true, function(result){
							actors = result;
						});
					}
				}
				else if('end' == nodeAttr)
				{
					actors = nodeName + '|' + nodeAttr;
				}
				
				var namesReturn = '';
				ajaxAsync('inner/flow/queryActorName.action', 'post', {'actorStr':actors}, true, function(nameStr){
					namesReturn = nameStr;
				});
				var names = namesReturn.split(';');
				var actorsArr = actors.split(';');
				var actorsLen = actorsArr.length;
				var groupDivAuditor = groupDivTmp.replace('#NEXT_NODE#', nodeName);
				var radioHtml = '';
				for(var j = 0; j < actorsLen; j++)
				{
					var actorx = actorsArr[j];
					var value = actorx + '|' + toNodeId;
					var radio = createRadioAuditor(value, names[j]);
					radioHtml += radio;
				}
				groupDivAuditor = groupDivAuditor.replace('#AUDITOR#', radioHtml);
				actorsHtml.push(groupDivAuditor);
			}
		}
	});
	var html = actorsHtml.join('');
	var actorsDiv = $('#actorsDiv');
	actorsDiv.html(html);
}

function createRadioAuditor(val, name)
{
	var radio = '<input class="flowComponent" onclick="changeReturnBack()" type="radio" value="' + val + '" name="auditorInfo" /> ' + name + '&nbsp;&nbsp;&nbsp;';
	return radio;
}

function changeReturnBack()
{
	var returnBack = $('#returnBack');
	returnBack.val('');
}

function clearActors()
{
	var actors = $('input:radio[name="auditorInfo"]');
	actors.attr('checked', false);
}

function getChildNodeText(xmlNode, childName)
{
	var child = xmlNode.getElementsByTagName(childName)[0].firstChild;
	if(child == null)
	{
		return '';
	}
	return child.nodeValue;
}

function setChildNodeText(xmlNode, childName, text)
{
	var textNode = xmlDom.createTextNode(childName);
	textNode.nodeValue = text;
	xmlNode.appendChild(textNode);
}

function doArrowSort(arrows)
{
	var arrowArray = new Array();
	var len = arrows.length;
	for(var i = 0; i < len; i++)
	{
		arrowArray.push(arrows[i]);
	}
	var temp = null;
	for(var i = 0; i < len; i++)
	{
		for(var j = i + 1; j < len; j++)
		{
			var ai = arrowArray[i];
			var aiSort = ai.getAttribute('sort') == null ? 10 : parseInt(ai.getAttribute('sort'), 10);
			var aj = arrowArray[j];
			var ajSort = aj.getAttribute('sort') == null ? 10 : parseInt(aj.getAttribute('sort'), 10);
			if(aiSort > ajSort)
			{
				temp = arrowArray[i];
				arrowArray[i] = arrowArray[j];
				arrowArray[j] = temp;
			}
		}
	}
	return arrowArray;
}

